package th.stripes.config;

import com.google.inject.Inject;
import com.wideplay.warp.persist.Transactional;
import java.util.Date;

import javax.servlet.http.HttpSession;
import net.sourceforge.stripes.action.ActionBeanContext;
import th.dao.PenggunaDAO;
import th.model.Pengguna;

public class ableActionBeanContext extends ActionBeanContext {

    public static final String USER_ID_KEY = "_KEY_USER";
    public static final String COUNTER_ID_KEY = "_COUNTER_ID";
    public static final String TRH_LOGIN = "_TRH_LOGIN";
    private Pengguna pengguna;
    private PenggunaDAO penggunaDAO;
    private String counterID;

    @Inject
    public ableActionBeanContext ( PenggunaDAO penggunaDAO ) {
        this.penggunaDAO = penggunaDAO;
    }

    @Transactional
    public Pengguna getCurrentUser() {
        if (pengguna == null) {
            HttpSession session = getRequest().getSession();
            if (session != null) {
                String userId = (String) session.getAttribute(USER_ID_KEY);
                if (userId != null) {
                    pengguna = penggunaDAO.findById(userId);                    
                }
            }
        }
        return pengguna;
    }   

    public void setCurrentUser(Pengguna user) {
        HttpSession session = getRequest().getSession(true);
        session.setAttribute(USER_ID_KEY, user.getNoKp());
        session.setAttribute(TRH_LOGIN, new Date());
        this.pengguna = user;
    }
    
    public void setCounter(String counter) {
        HttpSession session = getRequest().getSession(true); 
        session.setAttribute(COUNTER_ID_KEY, counter);
        counterID = counter;
    }
    
    public String getCounter() {
        if ("".equals(counterID) || counterID == null) {
            HttpSession session = getRequest().getSession();
            if (session != null) {
                counterID = (String) session.getAttribute(COUNTER_ID_KEY);
            }
        }
        return counterID;
    }

    public String getUserId() {
        return (String) getRequest().getSession().getAttribute(USER_ID_KEY);
    }

    public boolean isLoggedIn() {
        return getUserId() != null;
    }

    public void logout() {
        this.pengguna = null;
        HttpSession session = getRequest().getSession();
        if (session != null) {
            session.setAttribute(USER_ID_KEY, null);            
//            session.invalidate();
        }
    }
}
